package yang.yu.sessioncache.redis;

import com.alibaba.fastjson.JSON;
import yang.yu.sessioncache.SessionService;
import yang.yu.sessioncache.UserInfo;

import java.util.Optional;

/**
 * Created by yyang on 15/9/8.
 */
public class RedisSessionService implements SessionService {

    private String sessionId;

    private RedisClient client;

    public RedisSessionService(String sessionId) {
        this(sessionId, new RedisClient());
    }

    public RedisSessionService(String sessionId, RedisClient client) {
        this.sessionId = sessionId;
        this.client = client;
    }

    @Override
    public void init() {
        UserInfo userInfo = new UserInfo();
        userInfo.setLoginLogId("123");
        userInfo.setMacAddress("a8:20:66:0c:00:76");
        userInfo.setUsername("yyang");
        client.put(sessionId, JSON.toJSON(userInfo));
    }

    @Override
    public void shutdown() {
        client.remove(sessionId);
    }

    public Optional<UserInfo> getUserInfo() {
        Optional<Object> json = client.get(sessionId);
        return json.map(x -> JSON.parseObject(x.toString(), UserInfo.class));
    }

    @Override
    public Optional<String> getUsername() {
        return getUserInfo().map(UserInfo::getUsername);
    }

    @Override
    public Optional<String> getMacAddress() {
        return getUserInfo().map(UserInfo::getMacAddress);
    }

    @Override
    public Optional<String> getLoginLogId() {
        return getUserInfo().map(UserInfo::getLoginLogId);
    }
}
